Skip to content

The DataModel class

DataModel

Bases: BaseModel, SynalinksSaveable, DataModelOperators

The backend-dependent data model.

This data model uses Pydantic to provide, JSON schema inference and JSON serialization.

Examples:

Creating a DataModel for structured output

class AnswerWithReflection(synalinks.DataModel):
    thinking: str = synalinks.Field(
        description="Your step by step thinking",
    )
    reflection: str = synalinks.Field(
        description="The reflection about your thinking",
    )
    answer: str = synalinks.Field(
        description="The correct answer",
    )

language_model = synalinks.LanguageModel("ollama/mistral")

generator = synalinks.Generator(
    data_model=AnswerWithReflection,
    language_model=language_model,
)
Source code in synalinks/src/backend/pydantic/core.py
class DataModel(
    pydantic.BaseModel, SynalinksSaveable, DataModelOperators, metaclass=MetaDataModel
):
    """The backend-dependent data model.

    This data model uses Pydantic to provide, JSON schema inference
    and JSON serialization.

    Examples:

    **Creating a DataModel for structured output**

    ```python
    class AnswerWithReflection(synalinks.DataModel):
        thinking: str = synalinks.Field(
            description="Your step by step thinking",
        )
        reflection: str = synalinks.Field(
            description="The reflection about your thinking",
        )
        answer: str = synalinks.Field(
            description="The correct answer",
        )

    language_model = synalinks.LanguageModel("ollama/mistral")

    generator = synalinks.Generator(
        data_model=AnswerWithReflection,
        language_model=language_model,
    )
    ```
    """

    model_config: ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid")

    @classmethod
    def get_schema(cls):
        """Gets the JSON schema of the data model.

        Returns:
            (dict): The JSON schema.
        """
        return cls.model_json_schema()

    @classmethod
    def keys(cls):
        """Gets the JSON properties keys of the data model.

        Returns:
            (dict): The JSON schema.
        """
        schema = cls.get_schema()
        if "properties" in schema:
            return schema["properties"].keys()
        else:
            return []

    @classmethod
    def prettify_schema(cls):
        """Get a pretty version of the JSON schema for display.

        Returns:
            (str): The indented JSON schema.
        """
        import orjson

        return orjson.dumps(cls.get_schema(), option=orjson.OPT_INDENT_2).decode()

    @classmethod
    def to_symbolic_data_model(cls, name=None):
        """Converts the data model to a symbolic data model.

        Args:
            name (str): Optional. The name of the symbolic data model.
                If None, a name will be given automatically.

        Returns:
            (SymbolicDataModel): The symbolic data model.
        """
        return SymbolicDataModel(schema=cls.get_schema(), name=name)

    def get_json(self):
        """Gets the JSON value of the data model.

        Optional fields whose value is `None` are omitted from the output;
        the schema still declares them, so consumers should treat a missing
        key as `None`.

        Serialization is duck-typed (``serialize_as_any``): a field declared
        with a parent type (e.g. ``List[Entity]``) dumps each item with the
        *instance's* fields, so `Entity`/`Relation` subclasses keep their
        properties inside a generic `KnowledgeGraph`.

        Returns:
            (dict): The JSON value.
        """
        return self.model_dump(mode="json", exclude_none=True, serialize_as_any=True)

    def prettify_json(self):
        """Get a pretty version of the JSON object for display.

        Returns:
            (str): The indented JSON object.
        """
        import orjson

        return orjson.dumps(self.get_json(), option=orjson.OPT_INDENT_2).decode()

    def __repr__(self):
        return f"<DataModel json={self.get_json()}, schema={self.get_schema()}>"

    def get(self, key, default=None):
        """Get wrapper to make it easier to access JSON fields.

        Args:
            key (str): The key to access.
            default (any): The default value if key not found.
        """
        try:
            return self.__getattribute__(key)
        except Exception:
            return default

    def __getitem__(self, key):
        """Get item wrapper to make it easier to access JSON fields.

        Args:
            key (str): The key to access.
        """
        return self.__getattribute__(key)

    def to_json_data_model(self, name=None):
        """Converts the data model to a backend-independent data model.

        Args:
            name (str): Optional. The name of the json data model.
                If None, a name will be given automatically.

        Returns:
            (JsonDataModel): The backend-independent data model.
        """
        return JsonDataModel(
            schema=self.get_schema(),
            json=self.get_json(),
            name=name,
        )

    def get_nested_entity(self, key):
        """Retrieve a nested Entity and convert it to a JsonDataModel.

        The entity's `label` field is used as the discriminator to look up
        its schema in this model's `$defs`. Returns ``None`` when the value
        at ``key`` has no ``label`` or when the schema cannot be resolved.

        Args:
            key (str): The field name holding the nested entity.

        Returns:
            (JsonDataModel | None): A typed JsonDataModel wrapping the
                nested entity, or ``None`` if the value isn't an entity.
        """
        return self.to_json_data_model().get_nested_entity(key)

    def get_nested_entity_list(self, key):
        """Retrieve a nested Entity list and convert it to typed JsonDataModels.

        Each item is resolved against this model's `$defs` using its
        ``label`` field as discriminator. Items without a ``label`` field
        or an unresolved schema are skipped.

        Args:
            key (str): The field name holding the list of nested entities.

        Returns:
            (list[JsonDataModel]): One JsonDataModel per resolved entity.
        """
        return self.to_json_data_model().get_nested_entity_list(key)

    def _apply_op(self, op, *args):
        if any_meta_class(args):
            return run_maybe_nested(op.symbolic_call(*args))
        return run_maybe_nested(op(*args))

    def get_config(self):
        return self.get_json()

    @classmethod
    def from_config(cls, config):
        return cls(**config)

__getitem__(key)

Get item wrapper to make it easier to access JSON fields.

Parameters:

Name Type Description Default
key str

The key to access.

required
Source code in synalinks/src/backend/pydantic/core.py
def __getitem__(self, key):
    """Get item wrapper to make it easier to access JSON fields.

    Args:
        key (str): The key to access.
    """
    return self.__getattribute__(key)

get(key, default=None)

Get wrapper to make it easier to access JSON fields.

Parameters:

Name Type Description Default
key str

The key to access.

required
default any

The default value if key not found.

None
Source code in synalinks/src/backend/pydantic/core.py
def get(self, key, default=None):
    """Get wrapper to make it easier to access JSON fields.

    Args:
        key (str): The key to access.
        default (any): The default value if key not found.
    """
    try:
        return self.__getattribute__(key)
    except Exception:
        return default

get_json()

Gets the JSON value of the data model.

Optional fields whose value is None are omitted from the output; the schema still declares them, so consumers should treat a missing key as None.

Serialization is duck-typed (serialize_as_any): a field declared with a parent type (e.g. List[Entity]) dumps each item with the instance's fields, so Entity/Relation subclasses keep their properties inside a generic KnowledgeGraph.

Returns:

Type Description
dict

The JSON value.

Source code in synalinks/src/backend/pydantic/core.py
def get_json(self):
    """Gets the JSON value of the data model.

    Optional fields whose value is `None` are omitted from the output;
    the schema still declares them, so consumers should treat a missing
    key as `None`.

    Serialization is duck-typed (``serialize_as_any``): a field declared
    with a parent type (e.g. ``List[Entity]``) dumps each item with the
    *instance's* fields, so `Entity`/`Relation` subclasses keep their
    properties inside a generic `KnowledgeGraph`.

    Returns:
        (dict): The JSON value.
    """
    return self.model_dump(mode="json", exclude_none=True, serialize_as_any=True)

get_nested_entity(key)

Retrieve a nested Entity and convert it to a JsonDataModel.

The entity's label field is used as the discriminator to look up its schema in this model's $defs. Returns None when the value at key has no label or when the schema cannot be resolved.

Parameters:

Name Type Description Default
key str

The field name holding the nested entity.

required

Returns:

Type Description
JsonDataModel | None

A typed JsonDataModel wrapping the nested entity, or None if the value isn't an entity.

Source code in synalinks/src/backend/pydantic/core.py
def get_nested_entity(self, key):
    """Retrieve a nested Entity and convert it to a JsonDataModel.

    The entity's `label` field is used as the discriminator to look up
    its schema in this model's `$defs`. Returns ``None`` when the value
    at ``key`` has no ``label`` or when the schema cannot be resolved.

    Args:
        key (str): The field name holding the nested entity.

    Returns:
        (JsonDataModel | None): A typed JsonDataModel wrapping the
            nested entity, or ``None`` if the value isn't an entity.
    """
    return self.to_json_data_model().get_nested_entity(key)

get_nested_entity_list(key)

Retrieve a nested Entity list and convert it to typed JsonDataModels.

Each item is resolved against this model's $defs using its label field as discriminator. Items without a label field or an unresolved schema are skipped.

Parameters:

Name Type Description Default
key str

The field name holding the list of nested entities.

required

Returns:

Type Description
list[JsonDataModel]

One JsonDataModel per resolved entity.

Source code in synalinks/src/backend/pydantic/core.py
def get_nested_entity_list(self, key):
    """Retrieve a nested Entity list and convert it to typed JsonDataModels.

    Each item is resolved against this model's `$defs` using its
    ``label`` field as discriminator. Items without a ``label`` field
    or an unresolved schema are skipped.

    Args:
        key (str): The field name holding the list of nested entities.

    Returns:
        (list[JsonDataModel]): One JsonDataModel per resolved entity.
    """
    return self.to_json_data_model().get_nested_entity_list(key)

get_schema() classmethod

Gets the JSON schema of the data model.

Returns:

Type Description
dict

The JSON schema.

Source code in synalinks/src/backend/pydantic/core.py
@classmethod
def get_schema(cls):
    """Gets the JSON schema of the data model.

    Returns:
        (dict): The JSON schema.
    """
    return cls.model_json_schema()

keys() classmethod

Gets the JSON properties keys of the data model.

Returns:

Type Description
dict

The JSON schema.

Source code in synalinks/src/backend/pydantic/core.py
@classmethod
def keys(cls):
    """Gets the JSON properties keys of the data model.

    Returns:
        (dict): The JSON schema.
    """
    schema = cls.get_schema()
    if "properties" in schema:
        return schema["properties"].keys()
    else:
        return []

prettify_json()

Get a pretty version of the JSON object for display.

Returns:

Type Description
str

The indented JSON object.

Source code in synalinks/src/backend/pydantic/core.py
def prettify_json(self):
    """Get a pretty version of the JSON object for display.

    Returns:
        (str): The indented JSON object.
    """
    import orjson

    return orjson.dumps(self.get_json(), option=orjson.OPT_INDENT_2).decode()

prettify_schema() classmethod

Get a pretty version of the JSON schema for display.

Returns:

Type Description
str

The indented JSON schema.

Source code in synalinks/src/backend/pydantic/core.py
@classmethod
def prettify_schema(cls):
    """Get a pretty version of the JSON schema for display.

    Returns:
        (str): The indented JSON schema.
    """
    import orjson

    return orjson.dumps(cls.get_schema(), option=orjson.OPT_INDENT_2).decode()

to_json_data_model(name=None)

Converts the data model to a backend-independent data model.

Parameters:

Name Type Description Default
name str

Optional. The name of the json data model. If None, a name will be given automatically.

None

Returns:

Type Description
JsonDataModel

The backend-independent data model.

Source code in synalinks/src/backend/pydantic/core.py
def to_json_data_model(self, name=None):
    """Converts the data model to a backend-independent data model.

    Args:
        name (str): Optional. The name of the json data model.
            If None, a name will be given automatically.

    Returns:
        (JsonDataModel): The backend-independent data model.
    """
    return JsonDataModel(
        schema=self.get_schema(),
        json=self.get_json(),
        name=name,
    )

to_symbolic_data_model(name=None) classmethod

Converts the data model to a symbolic data model.

Parameters:

Name Type Description Default
name str

Optional. The name of the symbolic data model. If None, a name will be given automatically.

None

Returns:

Type Description
SymbolicDataModel

The symbolic data model.

Source code in synalinks/src/backend/pydantic/core.py
@classmethod
def to_symbolic_data_model(cls, name=None):
    """Converts the data model to a symbolic data model.

    Args:
        name (str): Optional. The name of the symbolic data model.
            If None, a name will be given automatically.

    Returns:
        (SymbolicDataModel): The symbolic data model.
    """
    return SymbolicDataModel(schema=cls.get_schema(), name=name)

MetaDataModel

Bases: DataModelOperators, DataModelTransforms, type(BaseModel)

The metaclass data model.

This class defines operations at the metaclass level. Allowing to use Synalinks Python operators with DataModel types.

Source code in synalinks/src/backend/pydantic/core.py
class MetaDataModel(DataModelOperators, DataModelTransforms, type(pydantic.BaseModel)):
    """The metaclass data model.

    This class defines operations at the metaclass level.
    Allowing to use Synalinks Python operators with `DataModel` types.
    """

    _apply_op = apply_symbolic_op

any_data_model(args=None, kwargs=None)

Check if any of the arguments are backend-dependent data models.

Parameters:

Name Type Description Default
args tuple

Optional. The positional arguments to check.

None
kwargs dict

Optional. The keyword arguments to check.

None

Returns:

Type Description
bool

True if any of the arguments are meta classes, False otherwise.

Source code in synalinks/src/backend/pydantic/core.py
def any_data_model(args=None, kwargs=None):
    """Check if any of the arguments are backend-dependent data models.

    Args:
        args (tuple): Optional. The positional arguments to check.
        kwargs (dict): Optional. The keyword arguments to check.

    Returns:
        (bool): True if any of the arguments are meta classes, False otherwise.
    """
    args = args or ()
    kwargs = kwargs or {}
    for x in tree.flatten((args, kwargs)):
        if is_meta_class(x):
            return True
    return False

any_meta_class(args=None, kwargs=None)

Check if any of the arguments are meta classes.

This happen when using a DataModel without instanciating it. In Synalinks this is used when declaring data models for schema inference.

Parameters:

Name Type Description Default
args tuple

Optional. The positional arguments to check.

None
kwargs dict

Optional. The keyword arguments to check.

None

Returns:

Type Description
bool

True if any of the arguments are meta classes, False otherwise.

Source code in synalinks/src/backend/pydantic/core.py
def any_meta_class(args=None, kwargs=None):
    """Check if any of the arguments are meta classes.

    This happen when using a `DataModel` without instanciating it.
    In Synalinks this is used when declaring data models for schema inference.

    Args:
        args (tuple): Optional. The positional arguments to check.
        kwargs (dict): Optional. The keyword arguments to check.

    Returns:
        (bool): True if any of the arguments are meta classes, False otherwise.
    """
    args = args or ()
    kwargs = kwargs or {}
    for x in tree.flatten((args, kwargs)):
        if is_meta_class(x):
            return True
    return False

is_data_model(x)

Returns whether x is a DataModel.

Parameters:

Name Type Description Default
x any

The object to check.

required

Returns:

Type Description
bool

True if x is a DataModel, False otherwise.

Source code in synalinks/src/backend/pydantic/core.py
def is_data_model(x):
    """Returns whether `x` is a DataModel.

    Args:
        x (any): The object to check.

    Returns:
        (bool): True if `x` is a DataModel, False otherwise.
    """
    return isinstance(x, DataModel)

is_meta_class(x)

Returns whether x is a meta class.

A meta class is a python type. This method checks if the data model provided if a meta class, allowing to detect if the DataModel have been instanciated. Meta classes are using in Synalinks when declaring data models for schema inference.

Parameters:

Name Type Description Default
x any

The object to check.

required

Returns:

Type Description
bool

True if x is a meta class, False otherwise.

Source code in synalinks/src/backend/pydantic/core.py
@synalinks_export(
    [
        "synalinks.utils.is_meta_class",
        "synalinks.backend.is_meta_class",
    ]
)
def is_meta_class(x):
    """Returns whether `x` is a meta class.

    A meta class is a python type. This method checks if the data model provided
    if a meta class, allowing to detect if the `DataModel` have been instanciated.
    Meta classes are using in Synalinks when declaring data models for schema inference.

    Args:
        x (any): The object to check.

    Returns:
        (bool): True if `x` is a meta class, False otherwise.
    """
    return inspect.isclass(x)

The Python operators of the data models, defined once.

SymbolicDataModel, JsonDataModel, DataModel and its metaclass MetaDataModel share these operators; each only says how to run an op (_apply_op). See the synalinks.ops tables for the exact semantics.

DataModelOperators

Python operators (+, &, |, ^, ~, in) on data models.

Source code in synalinks/src/backend/common/data_model_operators.py
class DataModelOperators:
    """Python operators (`+`, `&`, `|`, `^`, `~`, `in`) on data models."""

    def _apply_op(self, op, *args):
        """Run the `op` operation on `args` and return its output.

        Looked up on `type(self)`, so a `DataModel` class uses the one of its
        metaclass and an instance the one of its class.

        Args:
            op (Operation): The operation to run.
            *args: The operation inputs.
        """
        raise NotImplementedError

    def __add__(self, other):
        """Concatenates this data model with another.

        Args:
            other (JsonDataModel | DataModel | SymbolicDataModel):
                The other data model to concatenate with.

        Returns:
            (JsonDataModel | SymbolicDataModel): The concatenated data model,
                symbolic if one of them is a metaclass or symbolic data model.
        """
        from synalinks.src import ops

        return type(self)._apply_op(self, ops.Concat(), self, other)

    def __radd__(self, other):
        """Concatenates (reverse) another data model with this one.

        Args:
            other (JsonDataModel | DataModel | SymbolicDataModel):
                The other data model to concatenate with.

        Returns:
            (JsonDataModel | SymbolicDataModel): The concatenated data model,
                symbolic if one of them is a metaclass or symbolic data model.
        """
        from synalinks.src import ops

        return type(self)._apply_op(self, ops.Concat(), other, self)

    def __and__(self, other):
        """Perform a `logical_and` with another data model.

        If one of them is `None`, output `None`. If both are provided,
        then concatenates this data model with the other.

        Args:
            other (JsonDataModel | DataModel | SymbolicDataModel):
                The other data model to concatenate with.

        Returns:
            (JsonDataModel | SymbolicDataModel | None): The concatenated data
                model or `None` (see the `logical_and` table).
        """
        from synalinks.src import ops

        return type(self)._apply_op(self, ops.And(), self, other)

    def __rand__(self, other):
        """Perform a `logical_and` (reverse) with another data model.

        If one of them is `None`, output `None`. If both are provided,
        then concatenates the other data model with this one.

        Args:
            other (JsonDataModel | DataModel | SymbolicDataModel):
                The other data model to concatenate with.

        Returns:
            (JsonDataModel | SymbolicDataModel | None): The concatenated data
                model or `None` (see the `logical_and` table).
        """
        from synalinks.src import ops

        return type(self)._apply_op(self, ops.And(), other, self)

    def __or__(self, other):
        """Perform a `logical_or` with another data model.

        If one of them is `None`, output the other one. If both are provided,
        then concatenates this data model with the other.

        Args:
            other (JsonDataModel | DataModel | SymbolicDataModel):
                The other data model to concatenate with.

        Returns:
            (JsonDataModel | SymbolicDataModel | None): The concatenation if
                both are provided, the non-`None` data model if only one is,
                `None` otherwise (see the `logical_or` table).
        """
        from synalinks.src import ops

        return type(self)._apply_op(self, ops.Or(), self, other)

    def __ror__(self, other):
        """Perform a `logical_or` (reverse) with another data model.

        If one of them is `None`, output the other one. If both are provided,
        then concatenates the other data model with this one.

        Args:
            other (JsonDataModel | DataModel | SymbolicDataModel):
                The other data model to concatenate with.

        Returns:
            (JsonDataModel | SymbolicDataModel | None): The concatenation if
                both are provided, the non-`None` data model if only one is,
                `None` otherwise (see the `logical_or` table).
        """
        from synalinks.src import ops

        return type(self)._apply_op(self, ops.Or(), other, self)

    def __xor__(self, other):
        """Perform a `logical_xor` with another data model.

        If one of them is `None`, output the other one. If both are provided,
        then the output is `None`.

        Args:
            other (JsonDataModel | DataModel | SymbolicDataModel):
                The other data model.

        Returns:
            (JsonDataModel | SymbolicDataModel | None): `None` if both are
                provided, the non-`None` data model if only one is, `None`
                otherwise (see the `logical_xor` table).
        """
        from synalinks.src import ops

        return type(self)._apply_op(self, ops.Xor(), self, other)

    def __rxor__(self, other):
        """Perform a `logical_xor` (reverse) with another data model.

        If one of them is `None`, output the other one. If both are provided,
        then the output is `None`.

        Args:
            other (JsonDataModel | DataModel | SymbolicDataModel):
                The other data model.

        Returns:
            (JsonDataModel | SymbolicDataModel | None): `None` if both are
                provided, the non-`None` data model if only one is, `None`
                otherwise (see the `logical_xor` table).
        """
        from synalinks.src import ops

        return type(self)._apply_op(self, ops.Xor(), other, self)

    def __invert__(self):
        """Perform an inversion/negation (`logical_not`).

        Returns:
            (SymbolicDataModel | None): `None` for a concrete data model, a
                symbolic data model with the same schema for a metaclass or
                symbolic data model.
        """
        from synalinks.src import ops

        return type(self)._apply_op(self, ops.Not(), self)

    def __contains__(self, other):
        """Check if the schema of `other` is contained in this one,
        or if a string key exists.

        Args:
            other (SymbolicDataModel | DataModel | str): The other data model to compare
                with, or a string key to check for in the schema properties.

        Returns:
            (bool): True if all properties of `other` are present in this one,
                or if the string key exists in the schema properties.
        """
        if isinstance(other, str):
            return other in self.get_schema().get("properties", {})
        from synalinks.src.backend.common.json_schema_utils import contains_schema

        return contains_schema(self.get_schema(), other.get_schema())

__add__(other)

Concatenates this data model with another.

Parameters:

Name Type Description Default
other JsonDataModel | DataModel | SymbolicDataModel

The other data model to concatenate with.

required

Returns:

Type Description
JsonDataModel | SymbolicDataModel

The concatenated data model, symbolic if one of them is a metaclass or symbolic data model.

Source code in synalinks/src/backend/common/data_model_operators.py
def __add__(self, other):
    """Concatenates this data model with another.

    Args:
        other (JsonDataModel | DataModel | SymbolicDataModel):
            The other data model to concatenate with.

    Returns:
        (JsonDataModel | SymbolicDataModel): The concatenated data model,
            symbolic if one of them is a metaclass or symbolic data model.
    """
    from synalinks.src import ops

    return type(self)._apply_op(self, ops.Concat(), self, other)

__and__(other)

Perform a logical_and with another data model.

If one of them is None, output None. If both are provided, then concatenates this data model with the other.

Parameters:

Name Type Description Default
other JsonDataModel | DataModel | SymbolicDataModel

The other data model to concatenate with.

required

Returns:

Type Description
JsonDataModel | SymbolicDataModel | None

The concatenated data model or None (see the logical_and table).

Source code in synalinks/src/backend/common/data_model_operators.py
def __and__(self, other):
    """Perform a `logical_and` with another data model.

    If one of them is `None`, output `None`. If both are provided,
    then concatenates this data model with the other.

    Args:
        other (JsonDataModel | DataModel | SymbolicDataModel):
            The other data model to concatenate with.

    Returns:
        (JsonDataModel | SymbolicDataModel | None): The concatenated data
            model or `None` (see the `logical_and` table).
    """
    from synalinks.src import ops

    return type(self)._apply_op(self, ops.And(), self, other)

__contains__(other)

Check if the schema of other is contained in this one, or if a string key exists.

Parameters:

Name Type Description Default
other SymbolicDataModel | DataModel | str

The other data model to compare with, or a string key to check for in the schema properties.

required

Returns:

Type Description
bool

True if all properties of other are present in this one, or if the string key exists in the schema properties.

Source code in synalinks/src/backend/common/data_model_operators.py
def __contains__(self, other):
    """Check if the schema of `other` is contained in this one,
    or if a string key exists.

    Args:
        other (SymbolicDataModel | DataModel | str): The other data model to compare
            with, or a string key to check for in the schema properties.

    Returns:
        (bool): True if all properties of `other` are present in this one,
            or if the string key exists in the schema properties.
    """
    if isinstance(other, str):
        return other in self.get_schema().get("properties", {})
    from synalinks.src.backend.common.json_schema_utils import contains_schema

    return contains_schema(self.get_schema(), other.get_schema())

__invert__()

Perform an inversion/negation (logical_not).

Returns:

Type Description
SymbolicDataModel | None

None for a concrete data model, a symbolic data model with the same schema for a metaclass or symbolic data model.

Source code in synalinks/src/backend/common/data_model_operators.py
def __invert__(self):
    """Perform an inversion/negation (`logical_not`).

    Returns:
        (SymbolicDataModel | None): `None` for a concrete data model, a
            symbolic data model with the same schema for a metaclass or
            symbolic data model.
    """
    from synalinks.src import ops

    return type(self)._apply_op(self, ops.Not(), self)

__or__(other)

Perform a logical_or with another data model.

If one of them is None, output the other one. If both are provided, then concatenates this data model with the other.

Parameters:

Name Type Description Default
other JsonDataModel | DataModel | SymbolicDataModel

The other data model to concatenate with.

required

Returns:

Type Description
JsonDataModel | SymbolicDataModel | None

The concatenation if both are provided, the non-None data model if only one is, None otherwise (see the logical_or table).

Source code in synalinks/src/backend/common/data_model_operators.py
def __or__(self, other):
    """Perform a `logical_or` with another data model.

    If one of them is `None`, output the other one. If both are provided,
    then concatenates this data model with the other.

    Args:
        other (JsonDataModel | DataModel | SymbolicDataModel):
            The other data model to concatenate with.

    Returns:
        (JsonDataModel | SymbolicDataModel | None): The concatenation if
            both are provided, the non-`None` data model if only one is,
            `None` otherwise (see the `logical_or` table).
    """
    from synalinks.src import ops

    return type(self)._apply_op(self, ops.Or(), self, other)

__radd__(other)

Concatenates (reverse) another data model with this one.

Parameters:

Name Type Description Default
other JsonDataModel | DataModel | SymbolicDataModel

The other data model to concatenate with.

required

Returns:

Type Description
JsonDataModel | SymbolicDataModel

The concatenated data model, symbolic if one of them is a metaclass or symbolic data model.

Source code in synalinks/src/backend/common/data_model_operators.py
def __radd__(self, other):
    """Concatenates (reverse) another data model with this one.

    Args:
        other (JsonDataModel | DataModel | SymbolicDataModel):
            The other data model to concatenate with.

    Returns:
        (JsonDataModel | SymbolicDataModel): The concatenated data model,
            symbolic if one of them is a metaclass or symbolic data model.
    """
    from synalinks.src import ops

    return type(self)._apply_op(self, ops.Concat(), other, self)

__rand__(other)

Perform a logical_and (reverse) with another data model.

If one of them is None, output None. If both are provided, then concatenates the other data model with this one.

Parameters:

Name Type Description Default
other JsonDataModel | DataModel | SymbolicDataModel

The other data model to concatenate with.

required

Returns:

Type Description
JsonDataModel | SymbolicDataModel | None

The concatenated data model or None (see the logical_and table).

Source code in synalinks/src/backend/common/data_model_operators.py
def __rand__(self, other):
    """Perform a `logical_and` (reverse) with another data model.

    If one of them is `None`, output `None`. If both are provided,
    then concatenates the other data model with this one.

    Args:
        other (JsonDataModel | DataModel | SymbolicDataModel):
            The other data model to concatenate with.

    Returns:
        (JsonDataModel | SymbolicDataModel | None): The concatenated data
            model or `None` (see the `logical_and` table).
    """
    from synalinks.src import ops

    return type(self)._apply_op(self, ops.And(), other, self)

__ror__(other)

Perform a logical_or (reverse) with another data model.

If one of them is None, output the other one. If both are provided, then concatenates the other data model with this one.

Parameters:

Name Type Description Default
other JsonDataModel | DataModel | SymbolicDataModel

The other data model to concatenate with.

required

Returns:

Type Description
JsonDataModel | SymbolicDataModel | None

The concatenation if both are provided, the non-None data model if only one is, None otherwise (see the logical_or table).

Source code in synalinks/src/backend/common/data_model_operators.py
def __ror__(self, other):
    """Perform a `logical_or` (reverse) with another data model.

    If one of them is `None`, output the other one. If both are provided,
    then concatenates the other data model with this one.

    Args:
        other (JsonDataModel | DataModel | SymbolicDataModel):
            The other data model to concatenate with.

    Returns:
        (JsonDataModel | SymbolicDataModel | None): The concatenation if
            both are provided, the non-`None` data model if only one is,
            `None` otherwise (see the `logical_or` table).
    """
    from synalinks.src import ops

    return type(self)._apply_op(self, ops.Or(), other, self)

__rxor__(other)

Perform a logical_xor (reverse) with another data model.

If one of them is None, output the other one. If both are provided, then the output is None.

Parameters:

Name Type Description Default
other JsonDataModel | DataModel | SymbolicDataModel

The other data model.

required

Returns:

Type Description
JsonDataModel | SymbolicDataModel | None

None if both are provided, the non-None data model if only one is, None otherwise (see the logical_xor table).

Source code in synalinks/src/backend/common/data_model_operators.py
def __rxor__(self, other):
    """Perform a `logical_xor` (reverse) with another data model.

    If one of them is `None`, output the other one. If both are provided,
    then the output is `None`.

    Args:
        other (JsonDataModel | DataModel | SymbolicDataModel):
            The other data model.

    Returns:
        (JsonDataModel | SymbolicDataModel | None): `None` if both are
            provided, the non-`None` data model if only one is, `None`
            otherwise (see the `logical_xor` table).
    """
    from synalinks.src import ops

    return type(self)._apply_op(self, ops.Xor(), other, self)

__xor__(other)

Perform a logical_xor with another data model.

If one of them is None, output the other one. If both are provided, then the output is None.

Parameters:

Name Type Description Default
other JsonDataModel | DataModel | SymbolicDataModel

The other data model.

required

Returns:

Type Description
JsonDataModel | SymbolicDataModel | None

None if both are provided, the non-None data model if only one is, None otherwise (see the logical_xor table).

Source code in synalinks/src/backend/common/data_model_operators.py
def __xor__(self, other):
    """Perform a `logical_xor` with another data model.

    If one of them is `None`, output the other one. If both are provided,
    then the output is `None`.

    Args:
        other (JsonDataModel | DataModel | SymbolicDataModel):
            The other data model.

    Returns:
        (JsonDataModel | SymbolicDataModel | None): `None` if both are
            provided, the non-`None` data model if only one is, `None`
            otherwise (see the `logical_xor` table).
    """
    from synalinks.src import ops

    return type(self)._apply_op(self, ops.Xor(), self, other)

DataModelTransforms

Schema transforms (factorize, masks, prefix, suffix) on data models.

Kept apart from DataModelOperators so a DataModel instance does not get these names, which would shadow fields of the same name.

Source code in synalinks/src/backend/common/data_model_operators.py
class DataModelTransforms:
    """Schema transforms (`factorize`, masks, prefix, suffix) on data models.

    Kept apart from `DataModelOperators` so a `DataModel` instance does not
    get these names, which would shadow fields of the same name.
    """

    def factorize(self):
        """Factorizes the data model.

        Returns:
            (JsonDataModel | SymbolicDataModel): The factorized data model.
        """
        from synalinks.src import ops

        return type(self)._apply_op(self, ops.Factorize(), self)

    def in_mask(self, mask=None, pattern=None, recursive=True):
        """Applies a mask to **keep only** specified keys of the data model.

        Args:
            mask (list): The mask to be applied (list of keys).
            pattern (str): Optional. A regex pattern to match keys to keep.
            recursive (bool): Optional. Whether to apply the mask recursively.
                Defaults to `True`.

        Returns:
            (JsonDataModel | SymbolicDataModel): The data model with the mask applied.
        """
        from synalinks.src import ops

        return type(self)._apply_op(
            self, ops.InMask(mask=mask, pattern=pattern, recursive=recursive), self
        )

    def out_mask(self, mask=None, pattern=None, recursive=True):
        """Applies a mask to **remove** specified keys of the data model.

        Args:
            mask (list): The mask to be applied (list of keys).
            pattern (str): Optional. A regex pattern to match keys to remove.
            recursive (bool): Optional. Whether to apply the mask recursively.
                Defaults to `True`.

        Returns:
            (JsonDataModel | SymbolicDataModel): The data model with the mask applied.
        """
        from synalinks.src import ops

        return type(self)._apply_op(
            self, ops.OutMask(mask=mask, pattern=pattern, recursive=recursive), self
        )

    def prefix(self, prefix=None):
        """Add a prefix to **all** the data model fields (non-recursive).

        Args:
            prefix (str): the prefix to add

        Returns:
            (JsonDataModel | SymbolicDataModel): The data model with the prefix added.
        """
        from synalinks.src import ops

        return type(self)._apply_op(self, ops.Prefix(prefix=prefix), self)

    def suffix(self, suffix=None):
        """Add a suffix to **all** the data model fields (non-recursive).

        Args:
            suffix (str): the suffix to add

        Returns:
            (JsonDataModel | SymbolicDataModel): The data model with the suffix added.
        """
        from synalinks.src import ops

        return type(self)._apply_op(self, ops.Suffix(suffix=suffix), self)

factorize()

Factorizes the data model.

Returns:

Type Description
JsonDataModel | SymbolicDataModel

The factorized data model.

Source code in synalinks/src/backend/common/data_model_operators.py
def factorize(self):
    """Factorizes the data model.

    Returns:
        (JsonDataModel | SymbolicDataModel): The factorized data model.
    """
    from synalinks.src import ops

    return type(self)._apply_op(self, ops.Factorize(), self)

in_mask(mask=None, pattern=None, recursive=True)

Applies a mask to keep only specified keys of the data model.

Parameters:

Name Type Description Default
mask list

The mask to be applied (list of keys).

None
pattern str

Optional. A regex pattern to match keys to keep.

None
recursive bool

Optional. Whether to apply the mask recursively. Defaults to True.

True

Returns:

Type Description
JsonDataModel | SymbolicDataModel

The data model with the mask applied.

Source code in synalinks/src/backend/common/data_model_operators.py
def in_mask(self, mask=None, pattern=None, recursive=True):
    """Applies a mask to **keep only** specified keys of the data model.

    Args:
        mask (list): The mask to be applied (list of keys).
        pattern (str): Optional. A regex pattern to match keys to keep.
        recursive (bool): Optional. Whether to apply the mask recursively.
            Defaults to `True`.

    Returns:
        (JsonDataModel | SymbolicDataModel): The data model with the mask applied.
    """
    from synalinks.src import ops

    return type(self)._apply_op(
        self, ops.InMask(mask=mask, pattern=pattern, recursive=recursive), self
    )

out_mask(mask=None, pattern=None, recursive=True)

Applies a mask to remove specified keys of the data model.

Parameters:

Name Type Description Default
mask list

The mask to be applied (list of keys).

None
pattern str

Optional. A regex pattern to match keys to remove.

None
recursive bool

Optional. Whether to apply the mask recursively. Defaults to True.

True

Returns:

Type Description
JsonDataModel | SymbolicDataModel

The data model with the mask applied.

Source code in synalinks/src/backend/common/data_model_operators.py
def out_mask(self, mask=None, pattern=None, recursive=True):
    """Applies a mask to **remove** specified keys of the data model.

    Args:
        mask (list): The mask to be applied (list of keys).
        pattern (str): Optional. A regex pattern to match keys to remove.
        recursive (bool): Optional. Whether to apply the mask recursively.
            Defaults to `True`.

    Returns:
        (JsonDataModel | SymbolicDataModel): The data model with the mask applied.
    """
    from synalinks.src import ops

    return type(self)._apply_op(
        self, ops.OutMask(mask=mask, pattern=pattern, recursive=recursive), self
    )

prefix(prefix=None)

Add a prefix to all the data model fields (non-recursive).

Parameters:

Name Type Description Default
prefix str

the prefix to add

None

Returns:

Type Description
JsonDataModel | SymbolicDataModel

The data model with the prefix added.

Source code in synalinks/src/backend/common/data_model_operators.py
def prefix(self, prefix=None):
    """Add a prefix to **all** the data model fields (non-recursive).

    Args:
        prefix (str): the prefix to add

    Returns:
        (JsonDataModel | SymbolicDataModel): The data model with the prefix added.
    """
    from synalinks.src import ops

    return type(self)._apply_op(self, ops.Prefix(prefix=prefix), self)

suffix(suffix=None)

Add a suffix to all the data model fields (non-recursive).

Parameters:

Name Type Description Default
suffix str

the suffix to add

None

Returns:

Type Description
JsonDataModel | SymbolicDataModel

The data model with the suffix added.

Source code in synalinks/src/backend/common/data_model_operators.py
def suffix(self, suffix=None):
    """Add a suffix to **all** the data model fields (non-recursive).

    Args:
        suffix (str): the suffix to add

    Returns:
        (JsonDataModel | SymbolicDataModel): The data model with the suffix added.
    """
    from synalinks.src import ops

    return type(self)._apply_op(self, ops.Suffix(suffix=suffix), self)

apply_symbolic_op(self, op, *args)

Run op symbolically on args (the _apply_op of symbolic models).

Source code in synalinks/src/backend/common/data_model_operators.py
def apply_symbolic_op(self, op, *args):
    """Run `op` symbolically on `args` (the `_apply_op` of symbolic models)."""
    return run_maybe_nested(op.symbolic_call(*args))